//
//  SyllabusPageViewController.m
//  SchoolTimetable
//
//  Created by 梦里都是梦 on 16/1/6.
//  Copyright (c) 2016年 Yuanlinqian. All rights reserved.
//

#import "SyllabusPageViewController.h"
#import "ClassCell.h"
#import "TimerCell.h"
#import "IQActionSheetPickerView.h"
#import "ClassColorView.h"
#import "ClassModel.h"
#import "WeekClassModel.h"
#import "addClassWithMessageView.h"
#import "ClassMessageView.h"
#import <BmobSDK/BmobProFile.h>



@interface SyllabusPageViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,IQActionSheetPickerViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *backgroundView;
@property (weak, nonatomic) IBOutlet UILabel *dateLabel;
@property (weak, nonatomic) IBOutlet UIButton *leftDateBtn;
@property (weak, nonatomic) IBOutlet UIButton *rightDateBtn;
@property (weak, nonatomic) IBOutlet UICollectionView *tableTimeCollectionView;

// 选择的课程
@property(nonatomic,strong) UICollectionViewCell * choseCell;
@property(nonatomic,strong) UIImageView * choseImg;

// 添加课程选择器数据
@property(nonatomic,strong) NSArray * weekArray;
@property(nonatomic,strong) NSArray * startClassArray;
@property(nonatomic,strong) NSArray * endClassArray;

// 课程数据
@property (nonatomic,strong) NSMutableDictionary * dataDic;
// 增加课程判断
@property(nonatomic,assign) BOOL isAddClass;

@property(nonatomic,assign) NSInteger week;

@property(nonatomic,strong) addClassWithMessageView * addCWMView;

@property(nonatomic,strong) NSMutableArray * classColorViewsArr;

@property(nonatomic,strong) NSMutableArray * weeksArray;
@end

@implementation SyllabusPageViewController



-(NSMutableArray *)weeksArray
{
    if (!_weekArray) {
        _weeksArray  = [[NSMutableArray alloc]init];
        for (NSInteger i = 1; i <= 24; i++) {
            NSString * str = [NSString stringWithFormat:@"第%ld周",i];
            [_weeksArray addObject:str];
        }

    }
    return _weeksArray;
}
-(addClassWithMessageView *)addCWMView
{
     if (!_addCWMView)
     {
         NSArray  *apparray= [[NSBundle mainBundle]loadNibNamed:@"addClassWithMessageView" owner:nil options:nil];
         _addCWMView = [apparray firstObject];
         _addCWMView.frame = CGRectMake((SCREEN_SIZE.width-200)/2, -200, 200, 140);
         _addCWMView.backgroundColor = [UIColor orangeColor];
     }
    return _addCWMView;
}
-(NSMutableDictionary *)dataDic
{
    if (!_dataDic) {
        _dataDic = [[NSMutableDictionary alloc]init];
        for (NSInteger index = 0; index < 7; index++) {
            NSMutableArray * dataArray = [[NSMutableArray alloc]init];
            NSString * keyStr = [NSString stringWithFormat:@"%ld",index];
            [_dataDic setObject:dataArray forKey:keyStr];
            self.isAddClass = YES;
        }
    }
    
    return  _dataDic;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self customTableTimeCollectionView];

    self.automaticallyAdjustsScrollViewInsets = NO;
    [self saveDataToDeocument:NO];
    
    [self.view addSubview:self.addCWMView];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(synchronizeMessage:) name:SYN_MESSAGE object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(saveClassMessage:) name:SAVE_MESSAGE object:nil];
    self.navigationItem.title = @"课程表";
    [self saveDateToDeocumentisSave:NO];

    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self customClassByData];
}
// 从服务器上同步数据到本地
-(void)synchronizeMessage:(NSNotification *)notif
{
    BmobUser *bUser = [BmobUser getCurrentUser];
    if (bUser) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSString * classUrl = [bUser objectForKey:@"classUrl"];
            NSData * dicData = [NSData dataWithContentsOfURL:[NSURL URLWithString:classUrl]];
            
            NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:dicData];
            NSMutableDictionary *dataDic = [unarchiver decodeObjectForKey:@"dataDic"];
            [unarchiver finishDecoding];
            self.dataDic = dataDic;
            dispatch_async(dispatch_get_main_queue(), ^{
                for (ClassColorView * classColorView in self.classColorViewsArr) {
                    [classColorView removeFromSuperview];
                    
                }
                [self saveDataToDeocument:YES];
                [self customClassByData];

            });

        });
        
        
    }else{
        [SVProgressHUD showErrorWithStatus:@"请先登陆"];
    }


}
-(void)saveClassMessage:(NSNotification *)notif
{
    [self uploadDataithData];

}
// 保存本地数据到服务器
- (void)uploadDataithData
{
    BmobUser *user = [BmobUser getCurrentUser];
    if (user) {
        
   
    NSMutableData *dicData = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:dicData];
    [archiver encodeObject:self.dataDic forKey:@"dataDic"];
    [archiver finishEncoding];

    
//    [SVProgressHUD showWithStatus:@"上传课表"];
    
    [BmobProFile uploadFileWithFilename:@"用户课表" fileData:dicData block:^(BOOL isSuccessful, NSError *error, NSString *filename, NSString *url, BmobFile *file) {
        if (isSuccessful) {
            
            
            
            // 将上传的图片链接和用户联系起来
            
           
            [user setObject:file.url forKey:@"classUrl"];
            
            [user updateInBackgroundWithResultBlock:^(BOOL isSuc, NSError *err) {
                if (isSuc) {
//                    [SVProgressHUD showSuccessWithStatus:@"上传成功"];
                    
                }else {
//                    [SVProgressHUD showErrorWithStatus:[err localizedDescription]];
                }
            }];
            
            
            }else {
//                [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
                }
        
        
    } progress:^(CGFloat progress) {
        //上传进度
//        [SVProgressHUD showProgress:progress];
        
    }];
      }
}

-(void)customTableTimeCollectionView
{
    UICollectionViewFlowLayout * flowLayout = (UICollectionViewFlowLayout *)self.tableTimeCollectionView.collectionViewLayout;
    
    [self.tableTimeCollectionView registerNib:[UINib nibWithNibName:@"ClassCell" bundle:nil] forCellWithReuseIdentifier:@"ClassCell"];
    
    [self.tableTimeCollectionView registerNib:[UINib nibWithNibName:@"TimerCell" bundle:nil] forCellWithReuseIdentifier:@"TimerCell"];
    
    flowLayout.minimumLineSpacing = 0;

    flowLayout.minimumInteritemSpacing = 0;

    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 1, 0);
    
    
    // 设置数据源和代理
    self.tableTimeCollectionView.delegate = self;
    
    self.tableTimeCollectionView.dataSource = self;


}
- (IBAction)leftDateBtnPressed:(UIButton *)sender {
    
    NSString * str = self.dateLabel.text;
    NSInteger index = [self.weeksArray indexOfObject:str];
    if (index != 0) {
        self.week = [self.weeksArray indexOfObject:str];
        [self saveDateToDeocumentisSave:YES];
        NSString * weekStr = self.weeksArray[self.week-1];
        self.dateLabel.text = weekStr;
    }
;
}
- (IBAction)rightDateBtnPressed:(UIButton *)sender {
    NSString * str = self.dateLabel.text;
    NSInteger index = [self.weeksArray indexOfObject:str];
    if (index != self.weeksArray.count-1) {
        self.week = [self.weeksArray indexOfObject:str];
        [self saveDateToDeocumentisSave:YES];
        NSString * weekStr = self.weeksArray[self.week+1];
        self.dateLabel.text = weekStr;
    }

    
    
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 8;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 10;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    // 复用
    if (indexPath.row == 0 ) {
        TimerCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TimerCell" forIndexPath:indexPath];
     
                NSString * timeStr = [NSString stringWithFormat:@"%ld",indexPath.section+1];
                cell.timerLabel.text = timeStr;
        
        return cell;
       
    }
    else
    {
    ClassCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ClassCell" forIndexPath:indexPath];
        
    return cell;
    }
}
#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0 ) {
        return CGSizeMake(CELL_WIDTH-20, CELL_WIDTH);
    }
    else
        return CGSizeMake(CELL_WIDTH, CELL_WIDTH);

}


#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row != 0) {
      ClassCell * cell = (ClassCell *)[collectionView cellForItemAtIndexPath:indexPath];
        
        UIImageView * choesImg = self.choseImg;
        
        [choesImg removeFromSuperview];
        
        if (cell == self.choseCell) {
            self.choseCell = nil;
            
            self.choseImg = nil;
            
            [self customPickerToAddClassWith:indexPath];
        }
        else
        {
//            UIView * view = [[UIView alloc]init];
//            view.frame = CGRectMake(0, 0, CGRectGetWidth(cell.frame), CGRectGetHeight(cell.frame));
//            view.backgroundColor = [UIColor whiteColor];
//            view.alpha = 0.7;
            UIImageView * img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ic_tool_menu_addcourse_btn_img"]];
            
            [cell addSubview:img];
//            [view addSubview:img];
            
            img.frame = CGRectMake(5, 5, CGRectGetWidth(cell.frame)-10, CGRectGetHeight(cell.frame)-10);
            
            img.alpha = 0.5;
            
            self.choseImg = img;
            
            self.choseCell = cell;
        }

    }
}
#pragma mark - 创建添加课程选择器
-(void)customPickerToAddClassWith:(NSIndexPath *)indexPath
{
    IQActionSheetPickerView *picker = [[IQActionSheetPickerView alloc] initWithTitle:@"添加课程" delegate:self];
    
    self.weekArray = @[@"周一", @"周二", @"周三", @"周四", @"周五", @"周六", @"周日"];
    self.startClassArray = @[@"第1节", @"第2节", @"第3节", @"第4节", @"第5节", @"第6节", @"第7节", @"第8节", @"第9节", @"第10节"];
    self.endClassArray = @[@"第1节", @"第2节", @"第3节", @"第4节", @"第5节", @"第6节", @"第7节", @"第8节", @"第9节", @"第10节"];
    
    [picker setTitlesForComponents:@[self.weekArray,
                                     self.startClassArray,
                                     @[@"至"],
                                     self.endClassArray]];
    [picker selectIndexes:@[[NSNumber numberWithInteger:indexPath.row-1],[NSNumber numberWithInteger:indexPath.section],[NSNumber numberWithInteger:indexPath.section],[NSNumber numberWithInteger:indexPath.section]] animated:YES];
    [picker show];
    picker.tag = 10;
    
}
#pragma mark - 添加课程选择器回调
- (void)actionSheetPickerView:(IQActionSheetPickerView *)pickerView didSelectTitles:(NSArray*)titles{
    if (pickerView.tag == 10) {
        

    NSInteger weekDay =  [self.weekArray indexOfObject:titles[0]];
    
    NSInteger startClass = [self.startClassArray indexOfObject:titles[1]];
    
    NSInteger endClass = [self.endClassArray indexOfObject:titles[3]];
    if (startClass > endClass) {
        [SVProgressHUD showErrorWithStatus:@"课程时间设置不正确"];
    }
    else{
        
        self.isAddClass = YES;
        NSMutableArray * weekArr = [self.dataDic objectForKey:[NSString stringWithFormat:@"%ld",weekDay]];
        for (ClassModel * model in weekArr) {
            if (endClass < model.startTime || startClass > model.endTime) {
                
            }
            else
            {
                self.isAddClass = NO;
                [SVProgressHUD showErrorWithStatus:@"您选择时间段已有其他课程"];
            }
        }
        if (self.isAddClass == YES) {
            [UIView animateKeyframesWithDuration:1 delay:0 options:UIViewKeyframeAnimationOptionLayoutSubviews animations:^{
                self.addCWMView.frame = CGRectMake((SCREEN_SIZE.width-200)/2, SCREEN_SIZE.width/2, 200, 140);
            } completion:^(BOOL finished) {
                __weak typeof(self) weakSelf = self;
                _addCWMView.SMBlock = ^(NSString * name ,NSString * teacher,NSString * classroom){
                    ClassModel * model = [[ClassModel alloc]init];
                    
                    model.weekTime = weekDay;
                    model.startTime = startClass;
                    model.endTime = endClass;
                    UIColor * modelColor = [[UIColor alloc]initWithRed:(arc4random() % 255)/255.f green:(arc4random() % 255)/255.f blue:(arc4random() % 255)/255.f alpha:1];
                    model.viewColor = modelColor;
                    model.className = name;
                    model.classTea = teacher;
                    model.classRoom = classroom;
                    [weekArr addObject:model];
                    [weakSelf uploadDataithData];
                    [weakSelf saveDataToDeocument:YES];
                    [weakSelf customClassColorViewByModel:model];
                    
                            };
                        }];
            
                    }
                }
            }
    else if (pickerView.tag == 20)
    {
        self.dateLabel.text = titles[0];
        NSInteger week = [self.weeksArray indexOfObject:titles[0]]+1;
        self.week = week;
        [self saveDateToDeocumentisSave:YES];
    }
}
#pragma mark - 本地保存数据和读取数据
-(void)saveDataToDeocument:(BOOL)isKeep
{
    

    NSString * docmentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString * dataDirPath = [docmentPath stringByAppendingString:@"/ClassDataFile"];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    NSString * dataPath = [dataDirPath stringByAppendingString:@"/ClassData"];
    
    // 判断沙盒是否存在文件夹
    if ([fileManager fileExistsAtPath:dataDirPath]) {
        
    }
    else{
        // 创建文件夹
        [[NSFileManager defaultManager] createDirectoryAtPath:dataDirPath withIntermediateDirectories:YES attributes:nil error:nil];
        
    }
    if (isKeep) {
        NSMutableDictionary * dataDic = self.dataDic;
        [NSKeyedArchiver archiveRootObject:dataDic toFile:dataPath];
        
    }
    else{
        NSMutableDictionary * dataDic = [NSKeyedUnarchiver unarchiveObjectWithFile:dataPath];
        self.dataDic = dataDic;
    
    }

}
-(void)saveDateToDeocumentisSave:(BOOL)isSave
{
    
    
    NSString * docmentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString * dateDirPath = [docmentPath stringByAppendingString:@"/ClassDate"];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    NSString * datePath = [dateDirPath stringByAppendingString:@"/ClassDate"];
    
    // 判断沙盒是否存在文件夹
    if ([fileManager fileExistsAtPath:dateDirPath]) {
        
    }
    else{
        // 创建文件夹
        [[NSFileManager defaultManager] createDirectoryAtPath:dateDirPath withIntermediateDirectories:YES attributes:nil error:nil];
        
    }
    if (isSave) {
        NSString * weekStr = [NSString stringWithFormat:@"%ld",self.week];
        NSMutableDictionary * dateDic = [[NSMutableDictionary alloc]init];
        NSDate * newDate = [NSDate new];
        [dateDic setObject:weekStr forKey:@"周数"];
        [dateDic setObject:newDate forKey:@"日期"];
        [NSKeyedArchiver archiveRootObject:dateDic toFile:datePath];
        
    }
    else{
        NSMutableDictionary * dateDic = [NSKeyedUnarchiver unarchiveObjectWithFile:datePath];
        NSString * weekStr = [dateDic objectForKey:@"周数"];
        NSDate * oldDate = [dateDic objectForKey:@"日期"];
        if (!oldDate) {
            self.dateLabel.text = @"点击设置周数";
            return;
        }
        self.week = [self.weeksArray indexOfObject:weekStr];
        NSInteger day = [self getDaysFrom:oldDate To:[NSDate new]];
        NSString * weekString = [NSString stringWithFormat:@"第%ld周",day/7+[weekStr intValue]];
        self.dateLabel.text = weekString;
        
        
    }
    
}
-(NSInteger)getDaysFrom:(NSDate *)serverDate To:(NSDate *)endDate
{
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    [gregorian setFirstWeekday:2];
    
    //去掉时分秒信息
    NSDate *fromDate;
    NSDate *toDate;
    [gregorian rangeOfUnit:NSCalendarUnitDay startDate:&fromDate interval:NULL forDate:serverDate];
    [gregorian rangeOfUnit:NSCalendarUnitDay startDate:&toDate interval:NULL forDate:endDate];
    NSDateComponents *dayComponents = [gregorian components:NSCalendarUnitDay fromDate:fromDate toDate:toDate options:0];
    
    return dayComponents.day;
}
-(void)customClassByData
{
    for (ClassColorView * classColorView in self.classColorViewsArr) {
        [classColorView removeFromSuperview];
    }
    self.classColorViewsArr = @[].mutableCopy;
    for (NSInteger index = 0; index < 7; index++) {
        NSString * str = [NSString stringWithFormat:@"%ld",index];
        NSMutableArray *dataArr = [self.dataDic objectForKey:str];
        for (ClassModel * model in dataArr) {
            [self customClassColorViewByModel:model];
        }
    }
}
-(void)customClassColorViewByModel:(ClassModel *)model
{
//[self customLocalNotificationByModel:model];
    NSArray  *apparray= [[NSBundle mainBundle]loadNibNamed:@"ClassColorView" owner:nil options:nil];
    ClassColorView * classColorView = [apparray firstObject];
    classColorView.weekTime = model.weekTime;
    classColorView.startTime = model.startTime;
    classColorView.endTime = model.endTime;
    classColorView.classNameLabel.text = model.className;
    classColorView.classRoomLabel.text = [NSString stringWithFormat:@"@%@",model.classRoom];
    classColorView.classTeacherLabel.text = model.classTea;
    classColorView.layer.cornerRadius = 5;
    classColorView.frame = CGRectMake(CELL_WIDTH * (model.weekTime+1) -20+1, (CELL_WIDTH+1) * model.startTime+1,CELL_WIDTH-2, CELL_WIDTH * (model.endTime - model.startTime +1)+(model.endTime - model.startTime)-2);
    
    [self.tableTimeCollectionView addSubview:classColorView];
    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(classColorViewTapWithDeletedAndMessageWith:)];
    [classColorView addGestureRecognizer:tapGesture];
    classColorView.backgroundColor = model.viewColor;
    [self.classColorViewsArr addObject:classColorView];
}
- (void)classColorViewTapWithDeletedAndMessageWith:(UITapGestureRecognizer * )tap  {
    ClassColorView * classColorView = (ClassColorView *)tap.view;
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"课程信息" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * album = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIAlertController * deletedAlert = [[UIAlertController alloc]init];
        UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        UIAlertAction * sureDeleted = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSMutableArray * dataArr = [self.dataDic objectForKey:[NSString stringWithFormat:@"%ld",classColorView.weekTime]];
            for (ClassModel * model in dataArr) {
                if (model.startTime == classColorView.startTime) {
                    [dataArr removeObject:model];
                }
            }       [self saveDataToDeocument:YES];
                    [classColorView removeFromSuperview];
            [self.tableTimeCollectionView reloadData];
                    // 上传数据到服务器
                    [self uploadDataithData];
            [self cancelLocalNotificationWithKey:[NSString stringWithString:[NSString stringWithFormat:@"星期%ld第%ld节",classColorView.weekTime,classColorView.startTime]]];
            

            
        }];
        [deletedAlert addAction:sureDeleted];
        [deletedAlert addAction:cancel];
        [self presentViewController:deletedAlert animated:YES completion:^{
            
        }];

    }];
    UIAlertAction * camera = [UIAlertAction actionWithTitle:@"详情" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSArray  *apparray= [[NSBundle mainBundle]loadNibNamed:@"ClassMessageView" owner:nil options:nil];
        ClassMessageView * classMessageView = [apparray firstObject];
        classMessageView.frame = self.view.frame;
        classMessageView.classNameLabel.text = classColorView.classNameLabel.text;
        classMessageView.classTeacherLabel.text = classColorView.classTeacherLabel.text;
        classMessageView.classRoomLabel.text = classColorView.classRoomLabel.text;
        [self.view addSubview:classMessageView];

    }];
    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:album];
    [alert addAction:camera];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:^{
        
    }];
    
}
- (IBAction)setWeeksTap:(UITapGestureRecognizer *)sender {
        IQActionSheetPickerView *picker = [[IQActionSheetPickerView alloc] initWithTitle:@"设置当前周数" delegate:self];
        picker.titleFont = [UIFont systemFontOfSize:15];
        [picker setTitlesForComponents:@[self.weeksArray]];
        [picker show];
    picker.tag = 20;
   
}
-(void)customLocalNotificationByModel:(ClassModel *)model
{
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:3];
    
    /*
     
     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
     
     [formatter setDateFormat:@"HH:mm:ss"];
     
     NSDate *now = [formatter dateFromString:@"15:00:00"];//触发通知的时间
     
     */
    
    //chuagjian
    
    // 一个本地推送
    
    UILocalNotification *noti = [[UILocalNotification alloc] init];
    
    if (noti) {
        
        //设置推送时间
        NSArray * arr = @[@"星期一",@"星期二",@"星期三",@"星期四",@"星期五",@"星期六",@"星期天"];
        NSArray * timeArr = @[@"7:55:00",@"8:50:00",@"9:55:00",@"10:5:00",@"13:55:00",@"14:50:00",@"15:55:00",@"16:50:00",@"17:55:00",@"18:50:00"];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        
        [formatter setDateFormat:@"EEEE HH:mm:ss"];
//        [formatter setDateFormat:@"EEEE MMMM d, YYYY"];
        NSString * timeNow = [formatter stringFromDate:date];
//        NSLog(@"%@",timeNow);
        
        NSDate *now = [formatter dateFromString:[NSString stringWithFormat:@"%@ %@",arr[model.weekTime],timeArr[model.startTime]]];//触发通知的时间
//        NSLog(@"%@",[NSString stringWithFormat:@"%@ %@",arr[model.weekTime],timeArr[model.startTime]]);
        //设置时区
        noti.fireDate = now;
        noti.timeZone = [NSTimeZone defaultTimeZone];
        
        //设置重复间隔
        
        //        noti.repeatInterval = NSWeekCalendarUnit;
        
        //推送声音
        
        noti.soundName = UILocalNotificationDefaultSoundName;
        
        //内容
        
        noti.alertBody = @"推送内容";
        
        //显示在icon上的红色圈中的数子
        
        noti.applicationIconBadgeNumber = 1;
        
        //设置userinfo 方便在之后需要撤销的时候使用
        
        NSDictionary *infoDic = [NSDictionary dictionaryWithObject:@"name" forKey:[NSString stringWithFormat:@"星期%ld第%ld节",model.weekTime,model.startTime]];
        NSLog(@"%ld === %ld",model.weekTime,model.startTime);
        noti.userInfo = infoDic;
        
        //添加推送到uiapplication
        
        UIApplication *app = [UIApplication sharedApplication];
        
        [app scheduleLocalNotification:noti];
        
    }


}
-(void)cancelLocalNotificationWithKey:(NSString *)key {
//    NSLog(@"%@",key);
    // 获取所有本地通知数组
    NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
    
    for (UILocalNotification *notification in localNotifications) {
        NSDictionary *userInfo = notification.userInfo;
        if (userInfo) {
            // 根据设置通知参数时指定的key来获取通知参数
            NSString *info = userInfo[key];
            
            // 如果找到需要取消的通知，则取消
            if (info != nil) {
                [[UIApplication sharedApplication] cancelLocalNotification:notification];
                break;  
            }  
        }  
    }  
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
